﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BTv2.Controls;
using BTv2.Model;

namespace BTv2.UserControls
{
    /// <summary>
    /// Interaction logic for SensorGroupSettings.xaml
    /// </summary>
    public partial class SensorGroupSettings : UserControl
    {

        private Settings _settings;
        private SensorsController _scontroller;

        public SensorGroupSettings()
        {
            InitializeComponent();
        }

        public SensorGroupSettings(Settings s)
        {
            InitializeComponent();
            _settings = s;
        }

        private void TabLoaded(object sender, RoutedEventArgs e)
        {
            _scontroller = SensorsController.GetInstance();
            SensorGroupsListBox.ItemsSource = _scontroller.SensorGroups;
            SensorsListBox.ItemsSource = _scontroller.Sensors;
        }

        private void OpenSensorsGroupMenu(object sender, MouseButtonEventArgs e)
        {
            SensorsGroupMenu.IsOpen = !SensorsGroupMenu.IsOpen;
        }

        public async void SGAddSensorGroupClick(object sender, RoutedEventArgs e)
        {
            SensorsGroupMenu.IsOpen = false;
            CurrentSGListContainer.IsEnabled = true;
            CurrentSGListContainer.DataContext = new SensorGroup() { ID = 0, Sensors = new ObservableCollection<Sensor>(), BackupSensors = new ObservableCollection<Sensor>() };
            SensorsListBox.IsEnabled = true;
            SensorGroupsListBox.IsEnabled = false;
        }

        private void BackButtonClick(object sender, RoutedEventArgs e)
        {
            _settings.OpenMainSettings();
        }

        private async void SensorGroupsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var sg = SensorGroupsListBox.SelectedItem as SensorGroup;
            try
            {

                sg.BackupSensors = new ObservableCollection<Sensor>(sg.Sensors);
                CurrentSGListContainer.IsEnabled = true;
                CurrentSGListContainer.DataContext = sg;
                SensorsListBox.IsEnabled = true;
                SensorGroupsListBox.IsEnabled = false;
            }
            catch
            {
                //when deselecting its called
            }
            try
            {
                SensorsListBox.ItemsSource = await _scontroller.GetFilteredSensorList(sg);
            }
            catch
            {
                SensorsListBox.ItemsSource = _scontroller.Sensors;
            }
        }

        private void SGCancelButton_Click(object sender, RoutedEventArgs e)
        {
            SensorGroupsListBox.UnselectAll();
            var sg = CurrentSGListContainer.DataContext as SensorGroup;
            sg.Sensors = sg.BackupSensors;
            CurrentSGListContainer.DataContext = null;
            SensorsListBox.IsEnabled = false;
            SensorGroupsListBox.IsEnabled = true;
            CurrentSGListContainer.IsEnabled = false;
        }

        private async void SGDeleteButton_Click(object sender, RoutedEventArgs e)
        {
            SensorGroup _sg = CurrentSGListContainer.DataContext as SensorGroup;
            bool result = await _scontroller.DeleteSensorGroup(_sg);
            if (result)
            {
                _scontroller.SensorGroups.Remove(_sg);

                Task.Run(async () =>
                {
                    NotificationsController.GetInstance().AddNotification("" + _sg.Name + " was Deleted", NotificationsController.CryticalNotificationType);
                    await UsersController.GetInstance().SendWarningSensorGroupMail("", _sg.Name, UsersController.GetInstance().GetLoggedUser().UserName);
                });
            }
            SensorGroupsListBox.UnselectAll();
            CurrentSGListContainer.DataContext = null;
            SensorsListBox.IsEnabled = false;
            SensorGroupsListBox.IsEnabled = true;
            CurrentSGListContainer.IsEnabled = false;
        }

        private async void SGSaveButton_Click(object sender, RoutedEventArgs e)
        {
            SensorGroup _sg = CurrentSGListContainer.DataContext as SensorGroup;
            int sgid = _sg.ID;
            bool result = await _scontroller.SaveSensorGroup(_sg, SGNameTextBox.Text, SGDescrptionTextBox.Text);
            if (result)
            {
                _sg.Name = SGNameTextBox.Text;
                _sg.Description = SGDescrptionTextBox.Text;
                if (sgid == 0)
                {
                    _scontroller.SensorGroups.Add(_sg);
                }
            }
            SensorGroupsListBox.UnselectAll();
            CurrentSGListContainer.DataContext = null;
            SensorsListBox.IsEnabled = false;
            SensorGroupsListBox.IsEnabled = true;
            CurrentSGListContainer.IsEnabled = false;
        }

        ListBox dragSource = null;


        private void SensorsListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListBox parent = (ListBox)sender;
            dragSource = parent;
            object data = GetDataFromListBox(dragSource, e.GetPosition(parent));

            if (data != null)
            {
                DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
            }
        }
        private static object GetDataFromListBox(ListBox source, Point point)
        {
            UIElement element = source.InputHitTest(point) as UIElement;
            if (element != null)
            {
                object data = DependencyProperty.UnsetValue;
                while (data == DependencyProperty.UnsetValue)
                {
                    data = source.ItemContainerGenerator.ItemFromContainer(element);
                    if (data == DependencyProperty.UnsetValue)
                    {
                        element = VisualTreeHelper.GetParent(element) as UIElement;
                    }
                    if (element == source)
                    {
                        return null;
                    }
                }
                if (data != DependencyProperty.UnsetValue)
                {
                    return data;
                }
            }
            return null;
        }

        private void CurrentSGSensorList_Drop(object sender, DragEventArgs e)
        {
            ListBox parent = (ListBox)sender;
            Sensor data = e.Data.GetData(typeof(Sensor)) as Sensor;
            ((IList)dragSource.ItemsSource).Remove(data);
            (parent.ItemsSource as ObservableCollection<Sensor>).Add(data);
        }

    }
}
